﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace HttpClientStudy.Core
{
    /// <summary>
    /// 管道方式 HttpClient客户端
    /// </summary>
    public class PipelineHttpClient
    {
        public List<DelegatingHandler> HttpMessageHandlers { get; set; }

        public PipelineHttpClient()
        {
            HttpMessageHandlers = new List<DelegatingHandler>()
            {
                new CustomHeadersHandler(),
                new LoggingHandler(),
            };

        }

        public PipelineHttpClient(List<DelegatingHandler> httpMessageHandlers)
        {
            HttpMessageHandlers = httpMessageHandlers;
            if (httpMessageHandlers == null || httpMessageHandlers?.Count == 0)
            {
                HttpMessageHandlers = new List<DelegatingHandler>();
            }
        }

        public void AddDelegatingHandler(DelegatingHandler handler)
        {
            HttpMessageHandlers.Add(handler);
        }

        public HttpClient CreateHttpClient()
        {
            //创建处理器链

            //最终处理器：最后一个请求处理程序，默认是SocketsHttpHandler.
            HttpMessageHandler currentPipeLine = new SocketsHttpHandler()
            {
                //自定义配置
                PooledConnectionLifetime = TimeSpan.FromSeconds(120),
            };
            //pipeline = new CustomHeadersHandler() { InnerHandler = pipeline};
            //pipeline = new LoggingHandler () { InnerHandler = pipeline};

            //倒序组装：完成后执行顺序与注册顺序一致
            HttpMessageHandlers.Reverse();
            for (int i = 0; i < HttpMessageHandlers.Count; i++)
            {
                HttpMessageHandlers[i].InnerHandler = currentPipeLine;
                currentPipeLine = HttpMessageHandlers[i];
            }

            // 利用管道创建HttpClient
            var httpClient = new HttpClient(currentPipeLine);

            return httpClient;
        }
    }
}
